package org.lzy.shop.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import org.lzy.shop.database.dao.CartItemDao
import org.lzy.shop.database.dao.GoodsSpecDao
import org.lzy.shop.database.entity.CartItemEntity
import org.lzy.shop.database.entity.GoodsSpecEntity
import org.lzy.shop.database.util.Converters

@Database(
    entities = [CartItemEntity::class, GoodsSpecEntity::class],
    version = 2,
    exportSchema = true
) // 启用exportSchema以便跟踪数据库架构变化
@TypeConverters(Converters::class)
abstract class CartDatabase : RoomDatabase() {
    // 添加缺少的DAO获取方法
    abstract fun cartItemDao(): CartItemDao
    abstract fun goodsSpecDao(): GoodsSpecDao

    companion object {
        @Volatile
        private var INSTANCE: CartDatabase? = null

        fun getDatabase(context: Context): CartDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    CartDatabase::class.java,
                    "cart_database"
                )
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}